package com.vilicode.controller;

import com.alibaba.excel.EasyExcel;
import com.vilicode.excel.ExcelUser;
import com.vilicode.excel.UserGroup;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller("/api")
public class ExcelController {
    // 生成导入模板（含3条示例数据）
    @RequestMapping(value = "/downTemplate", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) throws IOException {
        List<ExcelUser> userList = getUserList(3);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名，确保中文字符正确编码
        String fileName = URLEncoder.encode("用户模板.xlsx", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        EasyExcel.write(response.getOutputStream(), ExcelUser.class).sheet("用户信息").doWrite(userList);
    }

    private static List<ExcelUser> getUserList(int size) {
        List<ExcelUser> userList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            ExcelUser user = new ExcelUser();
            user.setUserId(i + 1);
            user.setUsername("username" + i);
            user.setPassword("password" + i);
            user.setEmail("email" + i + "@vilicode.com");
            user.setSex(i % 2);
            UserGroup userGroup = new UserGroup();
            userGroup.setName("管理组");
            user.setUserGroup(userGroup);
            user.setCreateAt(new Date());
            user.setCustomizeField(i);
            userList.add(user); // 添加到列表中
        }
        return userList;
    }
}
